<template>
	<el-container>
		<el-aside width="260px">
			<el-container>
				<el-main class="nopadding">
					<el-tree ref="category" @node-click="handleNodeClick" class="menu" node-key="label" :data="category" :default-expanded-keys="['系统日志']" current-node-key="系统日志" :highlight-current="true" :expand-on-click-node="false" default-expand-all style="padding: 10px">
						<template #default="{node, data}">
							<span class="custom-tree-node">
							<span class="label">
								{{ node.label }}
							</span>
							<span class="do" v-if="data.value>0">
								<el-button-group>
								<el-button icon="el-icon-edit" size="small" @click.stop="groupModify(node, data)"></el-button>
								<el-button icon="el-icon-delete" size="small" @click.stop="groupDelete(node, data)"></el-button>
								</el-button-group>
							</span>
							</span>
						</template>
					</el-tree>
				</el-main>
				<el-footer style="height:51px;">
					<el-button-group style="width: 100%">
						<el-button type="primary" size="small" icon="el-icon-plus" @click="addGroup" style="width:50%">新建分组</el-button>
						<el-button type="success" size="small" icon="el-icon-switch" @click.stop="addInterface" style="width:50%">新增接口</el-button>
					</el-button-group>
				</el-footer>
			</el-container>
		</el-aside>
		<el-container>
			<el-main class="nopadding">
				<el-container>
					<el-header>
						<div class="left-panel">
							<el-date-picker v-model="date" value-format="YYYY-MM-DD" @change="changeDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
						</div>
						<div class="right-panel">
							<div class="right-panel-search">
								<el-input v-model="search.name" placeholder="接口名称" clearable></el-input>
								<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
								<!--el-button type="text" icon="el-icon-takeaway-box" @click="recycle">回收站</el-button-->
							</div>
						</div>
					</el-header>
					<el-main class="nopadding">
						<jdTable ref="table" :apiObj="apiObj"  :params="search" stripe highlightCurrentRow @row-click="rowClick">
							<el-table-column label="序号" prop="id" width="60" align="center"></el-table-column>
							<el-table-column label="类型" prop="dataType" width="80" align="center">
								<template #default="scope">
									<span v-if="scope.row.dataType === 'sql'">
										<jd-icon-sql style="width: 30px;"/>
									</span>
									<span v-if="scope.row.dataType === 'data'">
										<jd-icon-static-data style="width: 30px;"/>
									</span>
									<span v-if="scope.row.dataType === 'api'">
										<jd-icon-api class="svg-icon" style="width: 30px;"/>
									</span>
								</template>
							</el-table-column>
							<el-table-column label="唯一编号" prop="name" min-width="150" show-overflow-tooltip="true"></el-table-column>
							<el-table-column label="功能说明" prop="remark" width="150"></el-table-column>
							<el-table-column label="数据库" prop="databaseId" min-width="150">
								<template #default="scope">
									{{ getDbName(scope.row.databaseId) }}
								</template>
							</el-table-column>
							<el-table-column label="请求方法" prop="requestMethod" width="100" align="center">
								<template #default="scope">
									<span v-if="scope.row.requestMethod == 1">增加</span>
									<span v-if="scope.row.requestMethod == 2">修改</span>
									<span v-if="scope.row.requestMethod == 3">查询</span>
									<span v-if="scope.row.requestMethod == 4">删除</span>
									<span v-if="scope.row.requestMethod == 6">GET</span>
									<span v-if="scope.row.requestMethod == 7">POST</span>
									<!-- <DictTag :options="Dict_LogType" :value="scope.row.requestMethod" ></DictTag> -->
								</template>
							</el-table-column>
							<el-table-column label="执行语句" prop="query" min-width="320">
								<template #default="scope">
									<div v-if="scope.row.dataType == 'sql'">
										<jd-ellipsis :text="scope.row.query"></jd-ellipsis>
									</div>
									<div v-if="scope.row.dataType == 'data'">
										<jd-ellipsis :text="scope.row.query"></jd-ellipsis>
									</div>
									<div v-if="scope.row.dataType == 'api'">
										<jd-ellipsis :text="$TOOL.getDomain(scope.row.url)"></jd-ellipsis>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
							<el-table-column label="操作" fixed="right" align="center" width="150">
								<template #default="scope">
									<el-button-group>
										<el-button text type="primary" @click="editInterface(scope.row)" class="button">编辑</el-button>
										<el-popconfirm title="确定要删除吗？" @confirm="delInterface(scope.row, scope.$index)">
											<template #reference>
												<el-button text type="primary" class="button">删除</el-button>
											</template>
										</el-popconfirm>
									</el-button-group>
								</template>
							</el-table-column>
						</jdTable>
					</el-main>
				</el-container>
			</el-main>
		</el-container>
	</el-container>

	<group-dialog v-if="dialog.group" ref="groupDialog" @success="handleSaveSuccess" @closed="dialog.group=false"></group-dialog>
	<save-dialog v-if="dialog.save" @close="refresh" ref="saveDialog" :group="search.type" :interfaceId="interfaceId" @success="handleSaveSuccess" @closed="dialog.save=false"></save-dialog>
	<preview-dialog v-if="dialog.preview" ref="previewDialog" :previewId="previewId" @success="handleSaveSuccess" @closed="dialog.preview=false"></preview-dialog>
</template>

<script>
	import groupDialog from './group'
	import saveDialog from './save'
	import previewDialog from './preview'

	export default {
		name: 'interface',
		components: {
			groupDialog,
			saveDialog,
			previewDialog,
		},
		data() {
			return {
				dialog: {
					group: false,
					save: false,
					preview: false,
				},
				interfaceId: 0,
				child:null,
				previewId: 0,
				infoDrawer: false,
				category: [
					{
						label: '来源分组',
						key: 'group',
						children: [
							{label: '默认分组',value: 'default'},
							{label: '本地数据',value: 'local'},
							{label: '远程数据',value: 'remote'},
							{label: '推送接口',value: 'push'}
						]
					},
					{
						label: '数据类型',
						key: 'data',
						children: [
							{label: '静态数据',value: 'data'},
							{label: 'SQL语句',value: 'sql'},
							{label: 'API接口',value: 'api'},
						]
					},

					{
						label: '时间维度',
						key: 'time',
						children: [
							{label: '近一周内',value: 'd7'},
							{label: '近半个月',value: 'd15'},
							{label: '近一个月',value: 'd30'}
						]
					}
				],
				date: [],
				apiObj: this.$API.app.interface.list,
				search: {
					keyword: ""
				},
				logsData: [],
				Dict_LogType: [],
				dbList: [],
				params:{
					pageNum:1,
					pageSize:20,
					appId:null
				}
			}
		},
		mounted(){
			this.getDict();
			this.getGroupList();
			this.$nextTick(()=>{
				this.child = this.$refs.category
			})
			// 自动展开菜单
			this.$store.commit('TOGGLE_IsCollapse', false);

		},
		created() {
			// 获取应用ID
			let appId = this.$route.query.appId;
			if (typeof(appId) != 'undefined'){
				this.search.appId = appId;
			}
			 this.getDataBase();
		},
		methods: {
			// 获取操作类型字典
			async getDict(){
				this.Dict_LogType = await this.Dict.get("sys_oper_type");
			},
			// 获取数据库连接
			async getDataBase(){
				var res = await this.$API.app.dbConn.listConnect.get(this.params);
				if (res.code == 200){
					this.dbList = res.data.rows;
				}
			},
			// 获取数据库名称
			getDbName(databaseId){
				var dbName = "-";
				if (databaseId != null){
					var dbNames = this.dbList.filter(item => item.connId == databaseId);
					if (dbNames !=null && dbNames.length>0){
						dbNames.forEach(item => {
							dbName = item.connName
						})
					}
				}
				return this.$TOOL.titleCase(dbName);
			},
			// 节点筛选
			handleNodeClick(data){
				// 获取父节点Key值
			    let  parentKey = this.getParentNodeKey(data)
			    if (parentKey == "group"){
			  	   this.search.type = data.value;
				   this.search.dataType=null;
				   this.search.time = null;
			    }else if (parentKey == "data"){
			  	   this.search.dataType = data.value;
				   this.search.type=null;
				   this.search.time = null;
			    }else if (parentKey == "time"){
			  	   this.search.time = data.value;
				   this.search.dataType = null;
				   this.search.type=null;
			    }
			},
			// 获取父节点Key
			getParentNodeKey(data){
				for (let i = 0; i < this.category.length; i++) {
					for (let j = 0; j < this.category[i].children.length; j++) {
						if (this.category[i].children[j].value === data.value){
							return this.category[i].key;
						}
					}
				}
				return "group";

			},
			// 关闭弹窗刷新数据
			refresh(){
				this.$refs.table.refresh();
			},
			// 日期筛选
			changeDate(){
				if (this.date != null){
					this.search.startTime=this.date[0]
					this.search.endTime=this.date[1]
				}
			},
			// 搜索
			upsearch(){
				this.$refs.table.refresh();
			},
			// 获取接口分组列表
			async getGroupList(){
				var res = await this.$API.app.interface.getGroupList.get();
				if (res.code == 200){
					for (let i = 0; i < res.data.length; i++) {
						let data={label: res.data[i].groupName,value: res.data[i].id}
						this.category[0].children.push(data);
					}
				}
			},
			rowClick(row,column){
				// 忽略操作列区域点击效果
				if(column && column.label=='操作'){
					return;
				}
				this.dialog.preview = true
				this.previewId = row.id;
				this.$nextTick(() => {
					this.$refs.previewDialog.open('show').setData(row)
				})
			},
			// 增加分组
			async addGroup(){
				this.$prompt('分组名称', '新建分组', {
					inputPlaceholder: '请输入一个方便识别的分组名称',
					inputPattern: /\S/,
					inputErrorMessage: '分组名称不能为空'
				})
				.then(async ({ value }) => {
					var data = {
						groupName: value
					}
					var res = await this.$API.app.interface.addGroup.post(data);
					if(res.code == 200){
						// 将分组名称加入到目录树中
						this.category[0].children.push({
							label: data.groupName,
							value: data.groupName
						});
						this.$message.success("操作成功")
					}else{
						this.$alert(res.message, "提示", {type: 'error'})
					}
				});
			},
			// 编辑分组
			async groupModify(node, data){
				var groupId = data.value;
				this.$prompt('分组名称', '编辑分组', {
					inputPlaceholder: '请输入一个方便识别的分组名称',
					inputPattern: /\S/,
					inputErrorMessage: '分组名称不能为空',
					inputValue: data.label
				})
				.then(async ({ value }) => {
					var data = {
						id: groupId,
						groupName: value
					}
					var res = await this.$API.app.interface.editGroup.put(data);
					if(res.code == 200){
						// 将分组名称加入到目录树中
						let updateNode = this.$refs.category.getNode(node);
						if (updateNode) {
							updateNode.data.label = value
						}
						this.$message.success("操作成功")
					}else{
						this.$alert(res.message, "提示", {type: 'error'})
					}
				});
			},
			// 删除分组
			async groupDelete(node, data){
				var res = await this.$API.app.interface.delGroup.delete(data.value);
				if (res.code == 200){
					let deleteNode = this.$refs.category.getNode(node);
					this.$refs.category.remove(deleteNode);
					this.$message.success("操作成功")
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
			},
			// 增加接口
			addInterface(){
				this.dialog.save = true;
				this.interfaceId = 0;
				this.$nextTick(() =>{
					this.$refs.saveDialog.open();
				})
			},
			// 编辑接口
			editInterface(data){
				this.dialog.save = true;
				this.interfaceId = data.id;
				this.$nextTick(() =>{
					this.$refs.saveDialog.open('edit');
				})
			},
			// 删除接口
			async delInterface(row, index){
				var res = await this.$API.app.interface.del.delete(row.id);
				if(res.code == 200){
					this.$refs.table.tableData.splice(index, 1);
					this.$message.success("删除成功")
				}else{
					this.$alert(res.msg, "提示", {type: 'error'})
				}
			},
			//树点击事件
			dictClick(data){
				this.dictType = data.dictType;
				this.$refs.table.reload({
					dictType: data.dictType
				})
			},
			//删除树
			dictDel(node, data){
				this.$confirm(`确定要删除"${data.dictType}"项吗？`, '提示', {
					type: 'warning'
				}).then(() => {
					this.showDictloading = true;

					//删除字典
					this.$API.system.dict.type.delType.delete(data.dictId);

					//删除节点是否为高亮当前 是的话 设置第一个节点高亮
					var dicCurrentKey = this.$refs.dict.getCurrentKey();
					this.$refs.dict.remove(data.dictId);

					if(dicCurrentKey == data.dictId){
						var firstNode = this.dictList[0];
						if(firstNode){
							this.dictType = firstNode.dictType;
							this.$refs.dict.setCurrentKey(firstNode.dictId);
							this.$refs.table.upData({
								dictType: firstNode.dictType
							})
						}else{
							this.listApi = null;
							this.$refs.table.tableData = []
						}
					}

					this.showDictloading = false;
					this.$message.success("操作成功")
				}).catch(() => {

				})
			},
		}
	}
</script>

<style lang="scss">
.svg-icon{
	width: 35px;
}
.custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;height:100%;padding-right:24px;}
.custom-tree-node .label {display: flex;align-items: center;height: 100%;}
.custom-tree-node .label .el-tag {margin-left: 5px;}
.custom-tree-node .do {display: none;}
.custom-tree-node .do i {margin-left:5px;color: #999;}
.custom-tree-node .do i:hover {color: #333;}

.custom-tree-node:hover {color:#409eff}
.custom-tree-node:hover .do {display: inline-block;animation: fadeIn;animation-duration: 1s;}
</style>
